package com.lxy.demo.filter;

import com.lxy.demo.entity.LoginUser;
import com.lxy.demo.utils.JwtUtil;
import com.lxy.demo.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
//OncePerRequestFilter因为spring版本不同，所以继承once的这个接口，一个请求只过滤一次
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }

        String id;
        try {
            Claims claims = JwtUtil.parseJWT(token);
             id = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token异常！");
        }

        //获取redis里的数据
        //设置key的值 getCacheObject获取值
        String key = "login:"+id;
        //获取的值是LoginUser对象，经过序列化过，之前存的是会
        LoginUser loginUser = redisCache.getCacheObject(key);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录！");
        }

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(auth);

        //放行
        filterChain.doFilter(request,response);
    }
}
